from typing import Generic, TypeVar, Optional
from pydantic import BaseModel

T = TypeVar('T')


class R(BaseModel, Generic[T]):
    code: int = 0
    data: Optional[T] = None
    msg: str = "ok"

    @classmethod
    def ok(cls, data: T = None, msg="ok") -> "R":
        return cls(code=0, data=data, msg=msg)

    @classmethod
    def fail(cls, msg: str = "fail") -> "R":
        return cls(code=1, msg=msg)

 
import json 
from typing import Any
from django.http import HttpRequest, HttpResponse
from ninja import NinjaAPI
from .jwt import DateEncoder


class BaseAPI(NinjaAPI):
    def create_response(self, 
                        request: HttpRequest, 
                        data: Any, *, 
                        status: int = 200, 
                        code: int = 0, 
                        msg: str = "ok",
                        temporal_response: HttpResponse = None,) -> HttpResponse:
        std_data = {
            "code": code,
            "data": data,
            "message": msg,
        }
        content = self.renderer.render(request, std_data, response_status=status)
        content_type = "{}; charset={}".format(
            self.renderer.media_type, self.renderer.charset
        )
        return HttpResponse(content, status=status, content_type=content_type)
    
    
class Response(HttpResponse):
	def __init__(self, data=None, msg='ok', code=0, *args, **kwargs):
		std_data = {
			"code": code,
			"data": data,
			"message": msg,
		}
		data = json.dumps(std_data, cls=DateEncoder)
		super().__init__(data, *args, **kwargs)